package org.ezjava.rpc.sb.provider.listener;

import lombok.extern.slf4j.Slf4j;
import org.ezjava.rpc.sb.provider.rpc.TFServer;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * @author Erik
 * @create 2021-08-10 15:55
 * @description
 **/
//@Component

@WebListener //需要配置扫描
@Slf4j
public class MyServletCtxListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("ctx inited");

        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        wac.getBean(TFServer.class).startServer();

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("ctx destroyed");
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        TFServer tfServer = wac.getBean(TFServer.class);
        if(tfServer != null) {
            tfServer.getServer().stop();
            log.info("shut down rpc");
        }

    }
}
